<template>
<basePages>	
  <view class="personal-container">
    <!-- 基本信息卡片 -->
    <view class="info-card">
      <view class="card-title">基本信息</view>
      
      <template v-if="userData">
        <view class="info-item" @click="openEdit('name')">
          <text class="item-label">姓名</text>
          <view class="item-content">
            <text class="item-value">{{ userData.name || '未设置' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>

        <view class="info-item" @click="openEdit('sex')">
          <text class="item-label">性别</text>
          <view class="item-content">
            <text class="item-value">{{ genderMap[userData.sex] || '未设置' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>

        <view class="info-item" @click="openEdit('age')">
          <text class="item-label">年龄</text>
          <view class="item-content">
            <text class="item-value">{{ userData.age || '未设置' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>

        <view class="info-item" @click="openEdit('phone')">
          <text class="item-label">手机号</text>
          <view class="item-content">
            <text class="item-value">{{ formatPhone(userData.phone) || '未绑定' }}</text>
            <view class="arrow-right"></view>
          </view>
        </view>
      </template>
      <view v-else class="loading-text">加载用户信息中...</view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="edit-btn" @click="openEdit('all')">编辑信息</button>
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <uni-popup-dialog
        mode="base"
        :title="editTitle"
        @confirm="submitForm"
        @close="closeEdit"
      >
        <uni-forms :model="editForm" :rules="formRules" ref="formRef">
          <uni-forms-item label="姓名" name="name">
            <uni-easyinput v-model="editForm.name" placeholder="请输入姓名" />
          </uni-forms-item>
          
          <uni-forms-item label="性别" name="sex">
            <uni-data-select
              v-model="editForm.sex"
              :localdata="genderOptions"
              placeholder="请选择性别"
            />
          </uni-forms-item>
          
          <uni-forms-item label="年龄" name="age">
            <uni-easyinput v-model="editForm.age" type="number" placeholder="请输入年龄" />
          </uni-forms-item>
          
          <uni-forms-item label="手机号" name="phone">
            <uni-easyinput v-model="editForm.phone" type="number" placeholder="请输入手机号" />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
 </basePages> 
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../../store/modules/useUserStore'

const store = useUserStore()
const editPopup = ref(null)
const formRef = ref(null)

// 表单初始数据
const editForm = ref({
  name: '',
  sex: '',
  age: '',
  phone: ''
})

// 当前编辑字段（单个字段编辑时使用）
const currentField = ref('all')

// 计算属性
const userData = computed(() => store.userData)
const genderMap = { male: '男', female: '女' }
const editTitle = computed(() => currentField.value === 'all' 
  ? '编辑个人信息' 
  : `修改${getFieldLabel(currentField.value)}`
)

const genderOptions = [
  { value: 'male', text: '男' },
  { value: 'female', text: '女' }
]

// 表单验证规则
const formRules = {
  name: { rules: [{ required: true, errorMessage: '请输入姓名' }] },
  sex: { rules: [{ required: true, errorMessage: '请选择性别' }] },
  age: {
    rules: [
      { required: true, errorMessage: '请输入年龄' },
      { format: 'number', errorMessage: '必须为数字' }
    ]
  },
  phone: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
    ]
  }
}

// 初始化加载数据
onMounted(() => {
  if (!store.userData) {
    try {
      store.loadFromStorage()
    } catch (err) {
      uni.showToast({ title: '数据加载失败', icon: 'none' })
      console.log(err)
    }
  }
})

// 打开编辑弹窗
const openEdit = (field) => {
  currentField.value = field
  initEditForm()
  editPopup.value.open()
}

// 初始化表单数据
const initEditForm = () => {
  if (currentField.value === 'all') {
    editForm.value = { ...userData.value }
  } else {
    editForm.value = { [currentField.value]: userData.value[currentField.value] }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 表单验证
    const validate = await formRef.value.validate()
    if (!validate) return
    
    // 合并修改数据
    const updatedData = currentField.value === 'all' 
      ? { ...editForm.value }
      : { [currentField.value]: editForm.value[currentField.value] }
    
    // 调用store更新
    const fullData = { ...userData.value, ...updatedData }
    await store.updateUserData(fullData)
    
    // 更新本地数据
    store.setUserData(fullData)
    
    uni.showToast({ title: '更新成功', icon: 'success' })
    editPopup.value.close()
  } catch (err) {
    console.error('更新失败:', err)
    uni.showToast({ title: '更新失败', icon: 'none' })
  }
}

// 关闭弹窗
const closeEdit = () => {
  editForm.value = { name: '', sex: '', age: '', phone: '' }
  editPopup.value.close()
}

// 字段标签映射
const getFieldLabel = (field) => {
  const labels = {
    name: '姓名',
    sex: '性别',
    age: '年龄',
    phone: '手机号'
  }
  return labels[field] || ''
}

// 手机号格式化
const formatPhone = (phone) => {
  return phone?.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') || '未绑定'
}

// 退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {

      if (res.confirm) {
        store.logout()
        console.log('用户点击确定');
        // 注意reLaunch 的url 要/斜杠开头
        uni.reLaunch({ url: '/pages/common/auth/login' })
      }
    }
  })
}
</script>

<style lang="scss">
.personal-container {
  min-height: 100vh;
  background-color: #F5F9FF;
  padding: 30rpx;
  
  .info-card {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(41, 135, 254, 0.08);
    
    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      padding-left: 20rpx;
      border-left: 8rpx solid #2987FE;
    }
    
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #F0F7FF;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-label {
        font-size: 30rpx;
        color: #333;
      }
      
      .item-content {
        display: flex;
        align-items: center;
        
        .item-value {
          margin-right: 20rpx;
          color: #666;
          font-size: 30rpx;
          max-width: 400rpx;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .arrow-right {
          width: 16rpx;
          height: 16rpx;
          border-top: 2rpx solid #2987FE;
          border-right: 2rpx solid #2987FE;
          transform: rotate(45deg);
        }
      }
      
      &:active {
        opacity: 0.8;
      }
    }
    
    .loading-text {
      color: #999;
      text-align: center;
      padding: 20rpx 0;
    }
  }
  
  .action-buttons {
    display: flex;
    flex-direction: column;
    padding: 40rpx 0;
    
    button {
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 44rpx;
      font-size: 32rpx;
      margin-bottom: 30rpx;
      
      &::after {
        border: none;
      }
      
      &.edit-btn {
        background-color: #2987FE;
        color: #fff;
        
        &:active {
          background-color: #1A6FD8;
        }
      }
      
      &.logout-btn {
        background-color: #fff;
        color: #2987FE;
        border: 1rpx solid #2987FE;
        
        &:active {
          background-color: #F5F9FF;
        }
      }
    }
  }
}
</style>